<template>
	<view class="warehouse-detail">
		<!-- 顶部导航栏 - 使用UniApp原生导航配置 -->
		<view class="navbar">
			<view class="navbar-content">
				<view class="navbar-left" @click="navigateBack">
					<uni-icons type="left" size="24" color="#333"></uni-icons>
					<view class="">关闭</view>
				</view>
				<view class="navbar-title">仓库详情</view>
				<view class="navbar-right">
					<view class="btn_summit" style="color: white" @click="edit">编辑</view>
					<view class="" style="margin-left: 50rpx"><uni-icons type="paperplane-filled" size="24" color="#333" @click="handleShare" class="mr-4"></uni-icons></view>
				</view>
			</view>
		</view>

		<!-- 轮播图区域 -->
		<view class="swiper-container">
			<scroll-view scroll-x="true" style="width: 100%; white-space: nowrap" class="image-scroll" show-scrollbar="false">
				<view class="swiper-item" v-for="(item, index) in warehouse.images" :key="index">
					<view class="img_box">
						<image :src="item.url" mode="aspectFit" class="swiper-image" :alt="item.desc"></image>
						<uni-icons type="clear" size="40" v-if="isEdit" class="clear" color="#409eff" @click="clearImg(item)"></uni-icons>
						
					</view>
						
					
				</view>
			 	
			</scroll-view>
        
			<view class="image-counter">{{ currentSwiperIndex + 1 }}/{{ warehouse.images.length }}</view>
		</view>
         <view v-if="isEdit" class="btn_summit" style="margin: 0 auto; margin-top: 50rpx;" @click="addPic('images')">添加仓库图片+</view>
		<!-- 基本信息卡片 -->
		<view class="info-card">
			<view class="info-header">
				<view class="name-container">
					<text class="warehouse-name">{{ warehouse.warehouse_name }}</text>
					<text class="warehouse-code">{{ warehouse.code }}</text>
				</view>
				<view class="status-tag">正常营业</view>
			</view>
			<view class="base-info" style="width: 50%">
				<view class="info-item">
					<uni-icons type="location" color="#ff3b30" size="18" class="info-icon"></uni-icons>
					<text class="info-text">{{ warehouse.address }}</text>
				</view>
				<view class="info-item">
					<uni-icons type="area" color="#007aff" size="18" class="info-icon"></uni-icons>
					<text class="info-text">
						<text v-if="!isEdit" class="text-bold">{{ warehouse.area }}</text>
						<input class="table-input" v-if="isEdit" type="number" v-model="warehouse.area" placeholder="输入面积（平方）" />
						平方米
					</text>
					<uni-icons type="compose" size="20" color="#409eff" v-if="isEdit" class="clear"></uni-icons>
				</view>
			</view>
			<view class="" style="display: flex; width: 100%">
				<view class="map-section">
					<text class="section-title">地理位置</text>
					<view class="map-container" style="background-color: aqua;" @click="openMap">
						<!-- 实际项目中可替换为地图组件 -->
						<map style="width: 100%; height: 100%" :markers="markers" :latitude="latitude" :longitude="longitude"></map>
					</view>
				</view>

				<!-- 温区信息 -->
				<view class="zone-section">
					<text class="section-title">温区信息</text>
					<view class="zone-list" v-if="warehouse.zones.length > 0">
						<view class="zone-item" v-for="(zone, index) in warehouse.zones" :key="index">
							<view class="zone-header">
								<text class="zone-type">{{ zone.name }}区</text>
								<text v-if="!isEdit" class="zone-volume">{{ zone.volume }} 立方米</text>
								<input class="table-input" v-if="isEdit" type="text" v-model="zone.volume" placeholder="请输入体积（立方）" />
							</view>
							<view class="progress-bar">
								<view
									class="progress-fill"
									:style="{
										width: zone.usage + '%',
										backgroundColor: zone.color
									}"
								></view>
							</view>
							<text class="usage-text">已使用 {{ zone.usage }}%</text>
						</view>
						<view v-if="warehouse.zones.length === 0" class="zone-list">
							<text>无数据</text>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 地图区域 -->

		<!-- 证照信息 -->
		<view class="cert-section">
			<text class="section-title">证照信息</text>
			<view class="cert-grid">
				<view class="cert-item" v-for="(cert, index) in warehouse.ctdCardValue" :key="index" @click="previewImage(index)">
					<image :src="cert.url" mode="aspectFill" class="cert-image" :alt="cert.name"></image>
					<view class="cert-name">{{ cert.name }}</view>
					<uni-icons type="clear" size="25" v-if="isEdit" color="#409eff" class="clear" @click="clearCert(cert)"></uni-icons>
				</view>
				<view v-if="isEdit" class="pic_add" style="background-color: #409eff" @click="addPic('ctdCardValue')">添加证照+</view>
			</view>
		</view>

		<!-- 业务范围 -->
		<view class="business-section">
			<text class="section-title">业务范围</text>
			<view class="tag-container">
				<view class="business-tag" v-for="(item, index) in warehouse.business" :key="index">
					<text>{{ item }}</text>
					<uni-icons type="clear" size="25" v-if="isEdit" color="#409eff" class="clear" @click="delBusiness(item)"></uni-icons>
				</view>
				<view class=""  v-if="isEdit"><input class="table-input" type="text" v-model="addBusinessItem" placeholder="输入项目名称" /></view>
				<view class="" v-if="isEdit" @click="addBusiness">+添加服务项目</view>
			</view>
		</view>

		<!-- 联系信息 -->
		<view class="contact-section">
			<text class="section-title">联系信息</text>
			<view class="contact-list">
				<view class="contact-item">
					<uni-icons type="compose" size="20" color="#409eff" v-if="isEdit" class="clear"></uni-icons>
					<view class="contact-icon bg-blue">
						<uni-icons type="user" size="20" color="#007aff"></uni-icons>
					</view>
					<view class="contact-inCfo">
						<text class="info-label">联系人</text>
						<text v-if="!isEdit" class="info-value">{{ warehouse.contact.person }}</text>
						<input class="table-input" v-if="isEdit" type="text" v-model="warehouse.contact.person" placeholder="输入联系人" />
					</view>
				</view>
				<view class="contact-item">
					<uni-icons type="compose" size="20" color="#409eff" v-if="isEdit" class="clear"></uni-icons>
					<view class="contact-icon bg-green">
						<uni-icons type="phone" size="20" color="#00c853"></uni-icons>
					</view>
					<view class="contact-info">
						<text class="info-label">联系电话</text>
						<text v-if="!isEdit" class="info-value">{{ warehouse.contact.phone }}</text>
						<input class="table-input" v-if="isEdit" type="text" placeholder="输入电话号" v-model="warehouse.contact.phone" />
					</view>
				</view>
			</view>
		</view>

		<!-- 底部操作栏 -->
		<view class="bottom-bar" v-if="isEdit">
			<button class="bottom-btn compare-btn" @click="addToCompare">退出编辑</button>
			<button class="bottom-btn contact-btn" @click="startCooperation">确认保存</button>
		</view>
	</view>
</template>

<script>
const CloudDB = uniCloud.importObject('getDb');
import { join } from 'lodash';
import strToLocation from '../untils/strToLocation.js';
import selectAndUploadFile from'../untils/selectAndUploadFile.js'
export default {
	name: 'warehouserInfo',
	props: {
		warehouseCode: {
			type: String,
			default: ''
		}
	},
	data() {
		return {
			// 仓库数据
			latitude: 39.9042, 
			longitude: 116.4074,
			isEdit: false,
			isMainBody: true,
			warehouse: {
				zones: [
					{ name: '常温', volume: 888, usage: 40, color: '#007aff' },
					{ name: '冷藏', volume: 888, usage: 30, color: '#00bcd4' },
					{ name: '冷冻', volume: 888, usage: 20, color: '#4fc3f7' }
				],
				business: ['普通货物存储', '冷链物流', '电商仓储', '城市配送', '物流包装', '供应链管理'],
				area: 0,
				contact: {
					person: '',
					phone: ''
				},
				images:[]
			},
			addBusinessItem: '',
			images: [],
			zones: ['常温区', '冷藏区', '冷冻区'],

			// 轮播图当前索引
			currentSwiperIndex: 0,
			// 是否收藏
			isCollected: false,
			markers:[]
		
		};
	},
	async mounted() {
		// 接收仓库ID参数
		await this.getWareHouse();
	
	},
	methods: {
		async getWareHouse() {
			console.log(this.warehouseCode);
			try {
				const res = await CloudDB.getDB('warehouse', { code: this.warehouseCode });
				console.log(res);
				if (res.code) {
					this.warehouse = { ...this.warehouse, ...res.data[0] };
					console.log('坐标',JSON.stringify(this.warehouse.location));
				this.longitude=strToLocation(this.warehouse.location).longitude
				this.latitude= strToLocation(this.warehouse.location).latitude,
				this.markers=[{
					id: 1,  // 标记唯一标识（必填）
					      latitude: strToLocation(this.warehouse.location).latitude,
					      longitude: strToLocation(this.warehouse.location).longitude,
					      width: 30,  // 标记宽度（rpx 或 px，根据平台调整）
					      height: 30, // 标记高度
					      iconPath:'../static/marker.png'
				}]
				
				}
				console.log(JSON.stringify(this.warehouse));
			} catch (e) {
				console.error(e);
			}
		},
		navigateBack() {
			this.$emit('close');
		},
		strToLocation,

		edit() {
			this.isEdit = !this.isEdit;
		},
		// 轮播图切换
		onSwiperChange(e) {
			this.currentSwiperIndex = e.detail.current;
		},
       async addPic(type){
		   
		  console.log(JSON.stringify(this.warehouse) ); 
		const res=await	selectAndUploadFile(`warehouse/${this.warehouseCode}`)
			
		const img={
			url:res.tempUrl,
			fileID:res.fileId
		}
		if(type==='ctdCardValue'){this.warehouse.ctdCardValue.push(img)}
		if(type==='images'){
			this.warehouse.images.push(img)
		}
		},
		// 切换收藏状态

		// 分享功能
		handleShare() {
			uni.showActionSheet({
				itemList: ['分享给微信好友', '分享到朋友圈', '复制链接'],
				success: (res) => {
					console.log('选中了第' + (res.tapIndex + 1) + '个选项');
					// 根据选择执行对应分享逻辑
				},
				fail: (err) => {
					console.log('取消分享', err);
				}
			});
		},

		// 预览图片
		previewImage(index) {
			const urls = this.warehouse.ctdCardValue.map((item) => item.url);
			uni.previewImage({
				urls: urls,
				current: index,
				success: (res) => {
					console.log('预览图片成功');
				},
				fail: (err) => {
					console.log('预览图片失败', err);
				}
			});
		},

		// 拨打电话
		makePhoneCall() {
			uni.makePhoneCall({
				phoneNumber: this.warehouse.contactPhone,
				fail: (err) => {
					console.log('拨打电话失败', err);
				}
			});
		},

		// 发送短信
		sendMessage() {
			uni.openSMS({
				phoneNumber: this.warehouse.contactPhone,
				fail: (err) => {
					console.log('打开短信失败', err);
				}
			});
		},
		addBusiness() {
			if (!this.addBusinessItem) {
				uni.showToast({
					icon: 'fail',
					title: '请输入项目名'
				});
				return;
			}
			this.warehouse.business.push(this.addBusinessItem);
			this.addBusinessItem = '';
		},
		delBusiness(str) {
			const _this = this;
			const idx = _this.warehouse.business.findIndex((item) => item === str);
			console.log(idx);
			if (idx !== -1) {
				uni.showModal({
					title: `确认删除${str}?`,
					success(res) {
						if (res.confirm) {
							_this.warehouse.business.splice(idx, 1);
						}
					}
				});
			}
		},
		async clearImg(img){
			try {
			
				const idx = this.warehouse.images.findIndex((item) => item.fileID === img.fileID);
			
				if (idx === -1) {
					console.warn('未找到对应的图片数据');
					return;
				}
		
				const res = await CloudDB.deleteFile([img.fileID]);
							// 检查云存储删除是否成功
				if (res) {
					// 从本地数组中移除
					this.warehouse.images.splice(idx, 1);
					const r = await CloudDB.updateDB('warehouse', { _id: this.warehouse._id }, { images: this.warehouse.images });
					if (r.code) {
						uni.showToast({ title: '删除成功', icon: 'success' });
					}
				} else {
					console.error('云存储删除失败', res);
					uni.showToast({ title: '删除失败', icon: 'none' });
				}
			} catch (error) {
				console.error('删除过程出错:', error);
				uni.showToast({ title: '操作失败', icon: 'none' });
			}
			
			
			
		},
		async clearCert(cert) {
			try {
				console.log('要删除的证书信息:', JSON.stringify(cert));

				// 修正1：正确使用findIndex查找索引
				const idx = this.warehouse.ctdCardValue.findIndex((item) => item.fileID === cert.fileID);

				if (idx === -1) {
					console.warn('未找到对应的图片数据');
					return;
				}
				console.log(cert.fileID);
				// 先从云存储删除，成功后再更新本地数据
				const res = await CloudDB.deleteFile([cert.fileID]);
				console.log(JSON.stringify(res));
				// 检查云存储删除是否成功
				if (res) {
					// 从本地数组中移除
					this.warehouse.ctdCardValue.splice(idx, 1);
					const r = await CloudDB.updateDB('warehouse', { _id: this.warehouse._id }, { ctdCardValue: this.warehouse.ctdCardValue });
					if (r.code) {
						uni.showToast({ title: '删除成功', icon: 'success' });
					}
				} else {
					console.error('云存储删除失败', res);
					uni.showToast({ title: '删除失败', icon: 'none' });
				}
			} catch (error) {
				console.error('删除过程出错:', error);
				uni.showToast({ title: '操作失败', icon: 'none' });
			}
		},
		// 打开地图导航
		openMap() {
			// 实际项目中使用真实经纬度
			uni.openLocation({
				latitude: strToLocation(this.warehouse.location).latitude,
				longitude: strToLocation(this.warehouse.location).longitude,
				name: this.warehouse.warehouse_name,
				address: this.warehouse.address,
				scale: 18,
				fail: (err) => {
					console.log('打开地图失败', err);
				}
			});
		},

		// 加入对比
		addToCompare() {
			uni.showToast({
				title: '已加入对比',
				icon: 'none'
			});
		},

		// 洽谈合作
	async	startCooperation() {
		const area= Number(this.warehouse.area) 
		
		
		try{
			 const res=await CloudDB.updateDB('warehouse',{_id:this.warehouse._id},{...this.warehouse,area:area})	
			 console.log('更新？？？？？',res);
			if(res.code){
				uni.showToast({
					title:'更新成功'
				})
				this.isEdit=false
			}
		}catch(e){
			uni.showToast({
				title:'更新失败'+e
			})
		}
		   
		}
	}
};
</script>

<style scoped lang="scss">
@import '../common/global.scss';
@import '../common/variables.scss';
.warehouse-detail {
	background-color: #f5f5f5;
	position: relative;
	overflow-y: auto;
	max-width: 70vw;
	margin: 0 auto;
	height: 90vh;

	font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}

// 导航栏样式
.navbar {
	height: var(--status-bar-height) + 44px;
	padding-top: var(--status-bar-height);
	background-color: #ffffff;
	border-bottom: 1px solid #eeeeee;

	.navbar-content {
		display: flex;
		align-items: center;
		justify-content: space-between;
		height: 44px;
		padding: 0 16px;

		.navbar-left,
		.navbar-right {
			height: 44px;
			display: flex;
			align-items: center;
			justify-content: center;
		}

		.navbar-right {
			width: auto;
			display: flex;
			align-items: center;
		}

		.navbar-title {
			flex: 1;
			text-align: center;
			font-size: 18px;
			font-weight: 500;
			color: #333333;
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
		}
	}
}
.clear {
	position: absolute;
	bottom: 70%;
	right: 0;
	z-index: 10;
}
.pic_add {
	display: flex;
	align-items: center;
	width: 200rpx;
	height: 200rpx;
	justify-content: center;
	border-radius: 10rpx;
	background-color: white;
	border-color: #409eff;
	color: #fff;
}

// 轮播图样式
.swiper-container {
	display: flex;
	width: 100%;
	height: 230px;
	position: relative;
	align-items: center;
	margin-top: 20rpx;


	.swiper-item {
	
		display: inline-block;
      	margin: 5px 5px; /* 图片之间的间距 */
	
	}
	.img_box {
  		position: relative;
		display: inline-block;
	    width: 100%;
		height:  100%;
		margin: 20rpx 20rpx;
	}
	.swiper-image {
		height: 200px; /* 固定图片高度（可调整） */
		border-radius: 8px; /* 圆角美化 */
	}

	.image-counter {
		position: absolute;
		top: 10px;
		right: 10px;
		background-color: rgba(0, 0, 0, 0.5);
		color: #ffffff;
		font-size: 12px;
		padding: 2px 8px;
		border-radius: 12px;
	}
}

// 通用卡片样式
.info-card,
.map-section,
.cert-section,
.business-section,
.contact-section {
	background-color: #ffffff;
	border-radius: 10px;
	margin: 12px;
	padding: 16px;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

// 基本信息卡片
.info-header {
	display: flex;
	justify-content: space-between;
	align-items: flex-start;
	margin-bottom: 16px;

	.name-container {
		display: flex;
		align-items: center;
		flex-wrap: wrap;

		.warehouse-name {
			font-size: 20px;
			font-weight: 600;
			color: #333333;
			margin-right: 8px;
		}

		.warehouse-code {
			font-size: 12px;
			color: #007aff;
			background-color: #e8f4ff;
			padding: 2px 8px;
			border-radius: 12px;
			margin-top: 4px;
		}
	}

	.status-tag {
		font-size: 12px;
		color: #00c853;
		background-color: #e6f7e9;
		padding: 2px 8px;
		border-radius: 12px;
	}
}

.base-info {
	display: grid;
	grid-template-columns: 1fr;
	gap: 12px;
	margin-bottom: 16px;

	@media (min-width: 768px) {
		grid-template-columns: 1fr 1fr;
	}

	.info-item {
		position: relative;
		display: flex;
		align-items: flex-start;

		.info-icon {
			margin-top: 2px;
			margin-right: 8px;
		}

		.info-text {
			font-size: 14px;
			color: #666666;
			line-height: 1.5;
		}

		.text-bold {
			font-weight: 500;
			color: #333333;
		}
	}
}
// 温区信息
.zone-section {
	margin-top: 20px;
	width: 50%;
	padding: 0 30rpx;
	.zone-list {
		margin-top: 12px;
		display: flex;
		flex-direction: column;
		gap: 16px;
	}

	.zone-item {
		.zone-header {
			display: flex;
			justify-content: space-between;
			margin-bottom: 6px;

			.zone-type {
				font-size: 14px;
				color: #666666;
			}

			.zone-volume {
				font-size: 14px;
				color: #333333;
			}
		}

		.progress-bar {
			width: 100%;
			height: 8px;
			background-color: #f0f0f0;
			border-radius: 4px;
			overflow: hidden;

			.progress-fill {
				height: 100%;
				transition: width 0.5s ease;
			}
		}

		.usage-text {
			font-size: 12px;
			color: #999999;
			margin-top: 4px;
		}
	}
}

// 通用标题样式
.section-title {
	font-size: 16px;
	font-weight: 500;
	color: #333333;
	margin-bottom: 12px;
	display: block;
}

// 地图区域
.map-section {
	width: 50%;
	.map-container {
		width: 100%;
		height: 200px;
		border-radius: 8px;
		overflow: hidden;
		position: relative;

		.map-image {
			width: 100%;
			height: 100%;
		}

		.map-marker {
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
			animation: pulse 2s infinite;
		}

		.navigate-btn {
			position: absolute;
			bottom: 12px;
			right: 12px;
			background-color: #007aff;
			color: #ffffff;
			border: none;
			border-radius: 4px;
			padding: 6px 12px;
			font-size: 14px;
			display: flex;
			align-items: center;
			box-shadow: 0 2px 8px rgba(0, 122, 255, 0.3);

			.btn-icon {
				margin-right: 4px;
			}
		}
	}
}

// 证照信息
.cert-section {
	.cert-grid {
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		gap: 10px;

		@media (min-width: 768px) {
			grid-template-columns: repeat(4, 1fr);
		}

		.cert-item {
			position: relative;
			height: 120px;
			border-radius: 8px;
			overflow: hidden;
			background-color: #f5f5f5;

			.cert-image {
				width: 100%;
				height: 100%;
			}

			.cert-name {
				position: absolute;
				bottom: 0;
				left: 0;
				right: 0;
				background-color: rgba(0, 0, 0, 0.6);
				color: #ffffff;
				font-size: 12px;
				padding: 4px;
				white-space: nowrap;
				text-overflow: ellipsis;
				overflow: hidden;
			}
		}
	}
}

// 业务范围
.business-section {
	.tag-container {
		display: flex;
		flex-wrap: wrap;
		gap: 8px;

		.business-tag {
			background-color: #e8f4ff;
			position: relative;
			color: #007aff;
			font-size: 12px;
			padding: 6px 12px;
			border-radius: 16px;
		}
	}
}

// 联系信息
.contact-section {
	margin-bottom: 80px;

	.contact-list {
		display: flex;
		flex-direction: column;
		gap: 16px;
	}

	.contact-item {
		position: relative;
		display: flex;
		align-items: center;
		.contact-icon {
			width: 40px;
			height: 40px;
			border-radius: 50%;
			display: flex;
			align-items: center;
			justify-content: center;

			&.bg-blue {
				background-color: #e8f4ff;
			}

			&.bg-green {
				background-color: #e6f7e9;
			}
		}

		.contact-info {
			margin-left: 12px;
			flex: 1;

			.info-label {
				font-size: 12px;
				color: #999999;
			}

			.info-value {
				font-size: 16px;
				color: #333333;
				margin-top: 2px;
				display: block;
			}
		}
	}
}

// 操作按钮样式
.action-btn {
	width: 36px;
	height: 36px;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	border: none;

	&.call-btn {
		background-color: #00c853;
	}

	&.msg-btn {
		background-color: #007aff;
	}
}

// 底部操作栏
.bottom-bar {
	background-color: #ffffff;
	border-top: 1px solid #eeeeee;
	padding: 12px;
	display: flex;
	gap: 12px;

	.bottom-btn {
		flex: 1;
		height: 44px;
		border-radius: 8px;
		border: none;
		font-size: 16px;
		font-weight: 500;
		display: flex;
		align-items: center;
		justify-content: center;

		.btn-icon {
			margin-right: 6px;
		}
	}

	.compare-btn {
		background-color: #f5f5f5;
		color: #333333;
	}

	.contact-btn {
		background-color: #007aff;
		color: #ffffff;
	}
}

// 动画效果
@keyframes pulse {
	0% {
		transform: translate(-50%, -50%) scale(1);
		opacity: 1;
	}
	50% {
		transform: translate(-50%, -50%) scale(1.2);
		opacity: 0.8;
	}
	100% {
		transform: translate(-50%, -50%) scale(1);
		opacity: 1;
	}
}
</style>
